import { ipcRenderer, remote, IpcRendererEvent } from 'electron'
import { WPCProviderDelegate, WPCResolverDelegate } from 'electron-wpc'
import { IpcEvent, WindowOption } from 'app/type'
import { TAG_WIN_PROVIDER, BROAD_CAST_LIST } from 'app/config'

interface Handler {
    (resolve: Function, reject: Function, args: any): void
}
interface SubHandler {
    (event: IpcRendererEvent, args: any): void
}

// 打开新窗口
export function openWindow(option: WindowOption) {
    return ipcRenderer.invoke(IpcEvent.APP_WINDOW_CREATE, option)
}

// 关闭窗口
export function closeWindow(name?: string) {
    return ipcRenderer.invoke(IpcEvent.APP_WINDOW_CLOSE, name)
}

// 最大化/恢复窗口
export function maximizeWindow(name?: string) {
    return ipcRenderer.invoke(IpcEvent.APP_WINDOW_MAXIMIZE, name)
}

// 最小化/恢复窗口
export function minimizeWindow(name?: string) {
    return ipcRenderer.invoke(IpcEvent.APP_WINDOW_MINIMIZE, name)
}

// 是否全屏
export const isFullScreen = remote.getCurrentWindow().isFullScreen

// 切换全屏
export const setFullScreen = remote.getCurrentWindow().setFullScreen

// 监听消息
export function onWindowMessage(event: string, handler: Handler) {
    const providerDelegate = new WPCProviderDelegate()
    providerDelegate.on(event, handler)
}

// 发送消息
export async function sendWindowMessage(event: string, args: any, timeout = 60) {
    const resolverDelegate = new WPCResolverDelegate(TAG_WIN_PROVIDER)
    resolverDelegate.setTimeOut(timeout * 1000)
    await resolverDelegate.send(event, args)
}

// 获取可以订阅发布的信道
export function getCanSubscribeChannel() {
    return BROAD_CAST_LIST
}

// 订阅信道消息
export function subWindowMessage(channel: string, handler: SubHandler) {
    if (!BROAD_CAST_LIST.includes(channel)) {
        throw new Error('信道不存在！')
    }
    ipcRenderer.on(channel, handler)
}

// 发布信道消息
export function pubWindowMessage(channel: string, args: any) {
    if (!BROAD_CAST_LIST.includes(channel)) {
        throw new Error('信道不存在！')
    }
    ipcRenderer.send(channel, args)
}
